<?php
class OrderController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        // action body
    }

    public function completeAction()
    {
        $auth = new Application_Model_Auth();
		$rest = new Application_Model_Rest();
		if(!$auth->isLoggedIn()){
			$this->_redirect('/login');
		}
		$userid = $auth->getUserId();
		$req = $this->getRequest();
		if($req->isGet()){
			$orderid = $req->get('oid');

			//2016.5.19 by zhaoxin
			 $type = $req->get('type');
			//2016.5.19 by zhaoxin

			$preSubmit = $rest->getUserOrderPreSubmit($orderid);
			$this->view->preSubmit= '';
			if(empty($preSubmit)){
				$this->_redirect('/error');
			}
			$has_paid = $preSubmit->orderDetails[0]->has_paid;
			if($has_paid==1){
				$this->_redirect('/order/list');
			}
			$status = $preSubmit->orderDetails[0]->status;
			if($status==1){
				$this->_redirect('/order/details?oid='.$orderid);
			}
			//2016.5.19 by zhaoxin
			$this->view->type= $type;
			//2016.5.19 by zhaoxin

			$this->view->preSubmit= $preSubmit;
		}
		if ($req->isPost()) {
			$contact = $req->getPost('username');
			$mobile = $req->getPost('mobile');
			$address = $req->getPost('address');
			$delivery = $req->getPost('delivery');
			$payment = $req->getPost('payment');
			$pay_int = $req->getPost('pay_int');//1.daofu    2.weixin    3.taobao
			$appointment = $req->getPost('appointment');
			$voucherId = $req->getPost('voucherId');
			$remark = $req->getPost('remark');
			$id = $req->getPost('id');
			$presell_discount = $req->getPost('presell_discount');
			$distributerId = $req->getPost('distributerId');
			$type = $req->getPost('type');
			//echo json_encode(array('msg'=>$_POST));exit;
			if(!empty($distributerId)&&$type!='advance'){
				//todo check distributerId is open
				$res_open = $rest->getDistributerActive($distributerId);
				if($res_open!=true){
					echo json_encode(array("msg"=>"distributerClosed"));
					exit;
				}
			}
			if(empty($contact)||empty($mobile)
				||empty($address)||empty($appointment)
				||empty($payment)||empty($pay_int)||empty($delivery)||empty($id)){
				echo json_encode(array("msg"=>"parmsNull"));
				exit;
			}else{
				//$action = 'update&contact='.urlencode($contact).'&mobile='.$mobile.'&address='.urlencode($address).'&delivery='.$delivery.'&payment='.$payment.'&appointment='.$appointment.'&voucherId='.$voucherId.'&remark='.urlencode($remark).'&presell_discount='.$presell_discount.'&distributerId='.$distributerId;
				$action = 'update&contact='.$contact.'&mobile='.$mobile.'&address='.$address.'&delivery='.$delivery.'&payment='.$payment.'&appointment='.$appointment.'&voucherId='.$voucherId.'&remark='.$remark.'&presell_discount='.$presell_discount.'&distributerId='.$distributerId;
				$res_putUserOrder = $rest->putUserOrder($action,$id);
				if (!empty($res_putUserOrder)) {
					$oid = $res_putUserOrder->id;
					$custprice = $res_putUserOrder->custprice;
					if($custprice==0){
						//todo update has_paid
						$actionPay = 'pay&transactionId=1&platformId=1';
						$res_pay = $rest->putUserOrder($actionPay,$oid);
						echo json_encode(array('msg'=>'toSuccess'));
						exit;
					}
					/* $openIdNamespace = new Zend_Session_Namespace('open');
					$openId = $openIdNamespace->openId;
					include_once(APPLICATION_PATH."/../library/SendMsgToUser.php");
					$sendMsq = new SendMsgToUser();
					$send_res = $sendMsq->SendMessage($openId,"您的订单已在路上，点击查看详情http://shop.renrencaichang.com/order/details?uid=".$userid."&oid=".$oid); */
				//	$payment = $res_putUserOrder->payment;
					$has_paid = $res_putUserOrder->has_paid;
					$inserttime = $res_putUserOrder->inserttime;
					if($has_paid==1){
						echo json_encode(array("msg"=>"hasPaid"));
						exit;
					}
					$transactionId='';
					if($payment==2 && $pay_int ==3){
						$action_prepay = 'prepay&platform=taobao';
						$res_prepay = $rest->putUserOrder($action_prepay,$oid);
						$transactionId = $res_prepay->transaction_id;
					}
					echo json_encode(array("msg"=>"1","oid"=>$oid,"payment"=>$payment,"pay_int"=>$pay_int,"transactionId"=>$transactionId,"inserttime"=>$inserttime));
					exit;
				}else{
					echo json_encode(array("msg"=>"gotologin","inserttime"=>''));
					exit;
				}
			}
		}	
		
    }

    public function payAction()
    {
		$auth = new Application_Model_Auth();
		if(!$auth->isLoggedIn()){
			$rurl = '/order/list';
			$this->_redirect('/login?rurl='.$rurl);
		}
        $req = $this->getRequest();
		$rest = new Application_Model_Rest();
		if($req->isGet()){
			$oid= $req->get('oid');
			$res = $rest->getUserOrderDetails($oid);
			$res_userInfo = $rest->getUser();
			$this->view->res = $res;
			$this->view->res_userinfo = $res_userInfo;
		}
		if($req->isXMLHttpRequest()){
			$oid=$req->getPost('oid');
			$action_prepay = 'prepay&platform=taobao';
			$res_prepay = $rest->putUserOrder($action_prepay,$oid);
			if(empty($res_prepay)|| !array_key_exists('transaction_id',$res_prepay)){
				echo json_encode(array('msg'=>'error'));
				exit;
			}
			$transactionId = $res_prepay->transaction_id;
			if(empty($transactionId)){
				echo json_encode(array('msg'=>'error'));
				exit;
			}
			echo json_encode(array('msg'=>'success','transactionId'=>$transactionId));
			exit;
		}
    }

    public function successAction()
    {
		$auth = new Application_Model_Auth();
		if(!$auth->isLoggedIn()){
			$rurl = '/order/list';
			$this->_redirect('/login?rurl='.$rurl);
		}
		$tel = $auth->getUserName();
		$userid_session = $auth->getUserId();
		
		$req = $this->getRequest();
		if($req->isGet()){
			$orderid = $req->get('oid');
			$rest = new Application_Model_Rest();
			$res = $rest->getUserOrderDetails($orderid);
			$this->view->res = $res;
			$userid_order = $res->userid;
			if($userid_session !=$userid_order){
				$this->_redirect('/error');
			}
			if(empty($userid_order)){
				$userid = '';
			}if(empty($orderid)){
				$orderid ='';
			}
			$this->view->oid = $orderid;
			$this->view->uid = $userid_order;
			$this->view->tel = $tel;
		}
		
    }

    public function listAction()
    {
        $auth = new Application_Model_Auth();
		$rurl = '/order/list';
		if (!$auth->isLoggedIn()){
			$this->_redirect('/login?rurl='.$rurl);
		}
		$userid = $auth->getUserId();
		$rest = new Application_Model_Rest();
		$res = $rest->getUserOrderList($userid);
		$this->view->orderList = $res;
		$this->view->uid = $userid;
    }

    public function detailsAction()
    {
        $auth = new Application_Model_Auth();
		if(!$auth->isLoggedIn()){
			$this->_redirect('/login');
		}
		$session_uid = $auth->getUserId();
		$req = $this->getRequest();
		$rest= new Application_Model_Rest();
		if($req->isGet()){
			$act = $req->get('act');
			$oid = $req->get('oid');
			$res = $rest->getUserOrderDetails($oid);
			$order_userid = $res->userid;
			if($session_uid != $order_userid){
				$rurl='/order/list';
				$this->_redirect('/login?rurl='.$rurl);
			}
			
			if($act=='confirm'){
				$res_confirm = $rest->putUserOrder($act,$oid);
				$this->_redirect('order/status?oid='.$oid);
				//var_dump($res_confirm);
			}
			if($act=='cancel'){
				$res_cancel = $rest->putUserOrder($act,$oid);
				$this->_redirect('order/status?oid='.$oid);
				//var_dump($res_cancel);exit;
			}
			
			if(!empty($res))
				$this->view->res = $res;

			if(!empty($oid))
				$this->view->oid = $oid;
		}
		
    }

    public function appraiseAction()
    {
        $auth = new Application_Model_Auth();
		if(!$auth->isLoggedIn()){
			$this->_redirect('/login');
		}
		$userid = $auth->getUserId();
		$req = $this->getRequest();
		if($req->isGet()){
			$orderid = $req->get('oid');
			$shopid = $req->get('shopid');
			$rest = new Application_Model_Rest();
			$res = $rest->getUserOrderDetails($orderid);
			if(empty($orderid)||empty($shopid)||empty($res)){
				$this->_redirect('/error');
			}
			$isappraise = $res->isappraise;
			if($isappraise ==1){
				$this->_redirect('/site');
			}
			$this->view->res = $res;
			$this->view->orderid = $orderid;
			$this->view->shopid = $shopid;
		}
		if($req->isPost()){
			$data['freshScore']= $req->getPost('freshScore');
			$data['deliveryScore']= $req->getPost('sendScore');
			$data['priceScore']= $req->getPost('priceScore');
			$data['serviceScore']= $req->getPost('serviceScore');
			$data['colligateScore']= ($data['freshScore']+$data['deliveryScore']+$data['priceScore']+$data['serviceScore'])/4;
			$data['content']= $req->getPost('remark');
			$data['orderId']=$req->getPost('orderid');
			$data['clientId']= $req->getPost('shopid');
			$rest = new Application_Model_Rest();
			$post_res = $rest->postUserAppraise($data);
			//更改状态
			$action ='stas';
			$update_res = $rest->putUserOrder($action,$req->getPost('orderid'));
			if($post_res&&$update_res ){
				$this->_redirect('/order/status?oid='.$data['orderId']);
			}
		}
    
    }

    public function wxpayAction()
    {
		$this->_helper->layout->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		$req = $this->getRequest();
		if($req->isPost()){
			$orderid = $req->getPost('oid');
			if(empty($orderid)){
				echo json_encode(array("msg"=>"errorToOrderList"));
				exit;
			}
			$rest = new Application_Model_Rest();
			$orderDetails = $rest->getUserOrderDetails($orderid);
			if(empty($orderDetails)){
				echo json_encode(array("msg"=>"errorToSite"));
				exit;
			}
			$order_userid = $orderDetails->userid;
			$auth = new Application_Model_Auth();
			if(!$auth->isLoggedIn()){
				echo json_encode(array("msg"=>"errorToLogin"));
				exit;
			}
			$userid = $auth->getUserId();
			if($order_userid!=$userid){
				echo json_encode(array("msg"=>"errorToSite"));
				exit;
			}
			$has_paid = $orderDetails->has_paid;
			if($has_paid=='1'){
				echo json_encode(array("msg"=>"errorToOrderList"));
				exit;
			}else{
				$action_prepay = 'prepay&platform=weixin';
				$res_prepay = $rest->putUserOrder($action_prepay,$orderid);
				$transactionId = $res_prepay->transaction_id;
				$price = $orderDetails->custprice;
				if($price<=0){
					echo json_encode(array("msg"=>"errorToSite"));
					exit;
				}
				$wxAPI = new Application_Model_WXApi();
				$inserttime = $orderDetails->inserttime;
				$wxparams = $wxAPI->genereateWXPayParams($orderid,$transactionId,$price,$inserttime);
				if(empty($wxparams)){
					echo json_encode(array("msg"=>"errorToSite"));
					exit;
				}
				echo json_encode(array('msg'=>'success','wxparams'=>$wxparams,'orderid'=>$orderid,'uid'=>$userid,'transactionId'=>$transactionId,'price'=>$price));
				exit;
			}
	}	
    }

    public function zfbpayAction()
    {
        $req=$this->getRequest();
		if($req->isGet()){
			$orderid = $req->get('oid');
			$transactionId = $req->get('transactionId');
			$inserttime = $req->get('inserttime');
			if(empty($orderid)||empty($transactionId)){
				$this->_redirect('/error');
			}
			$rest = new Application_Model_Rest();
			$res = $rest->getUserOrderTransaction($transactionId);
			$transaction_status = $res->transaction_status;
			$has_paid = $res->order_has_paid;
			$price = $res->price;
			$ordercode = $res->ordercode;
			if($has_paid == '1'){
				echo '<script type="text/javascript">location.href="/order/success?oid='.$orderid.'"</script>';
				exit;
			}
			if($price<=0){
				$this->_redirect('/error');
			}
			$this->view->price = $price;
			$this->view->ordercode = $ordercode;
			$this->view->transactionId = $transactionId;
			$this->view->orderid = $orderid;
			$this->view->inserttime = $inserttime;
				
		}

		if($req->isPost()){
			$transactionId = $req->getPost('transactionId');
			$rest = new Application_Model_Rest();
			$res = $rest->getUserOrderTransaction($transactionId);
			$transaction_status = $res->transaction_status;
			$has_paid = $res->order_has_paid;
			if($has_paid == 1 && $transaction_status == 2){
				echo json_encode(array("msg"=>"has_paid"));
				exit;
			}else{
				echo json_encode(array("msg"=>"notPay"));
				exit;
			}
		}
		
    }

    public function zfbnotifyAction()
    {
        // action body
    }

    public function wxqueryAction()
    {
		include_once(APPLICATION_PATH ."/../library/WxPayPubHelper/WxPayPubHelper.php");
		$req = $this->getRequest();
		if($req->isGet()){
			$type = $req->get('type');
			if(!empty($type)&&$type=='kk'){
				$oid = $req->get('oid');
				// $auth = new Application_Model_Auth();
				// if(!$auth->isLoggedIn()){
					// $rurl = '/order/list';
					// $this->_redirect('login?rurl='.$rurl);
				// }
				// $uid = $auth->getUserId();
				$trade_no = $req->get('trade_no');
				if(empty($oid)||empty($trade_no)){
					$this->_redirect('/error');
				}else{
					$out_trade_no = $trade_no;
					$orderQuery = new OrderQuery_pub();
					$orderQuery->setParameter("out_trade_no","$out_trade_no");//商户订单号 
					//获取订单查询结果
					$orderQueryResult = $orderQuery->getResult();
					if ($orderQueryResult["return_code"] == "FAIL") {
						$this->_redirect('/error');
					}
					elseif($orderQueryResult["result_code"] == "FAIL"){
						$this->_redirect('/error');
					}
					else{
						$trade_state = $orderQueryResult['trade_state'];//交易状态
						$openid = $orderQueryResult['openid'];     //openid
						$is_subscribe = $orderQueryResult['is_subscribe'];//是否关注公众号
						$trade_type = $orderQueryResult['trade_type'];//交易类型
						$bank_type = $orderQueryResult['bank_type'];//付款银行
						$total_fee = $orderQueryResult['total_fee'];//总金额
						$fee_type = $orderQueryResult['fee_type'];//货币种类
						$transaction_id = $orderQueryResult['transaction_id'];//微信支付订单号
						$out_trade_no = $orderQueryResult['out_trade_no'];//商户订单号
						$time_end = $orderQueryResult['time_end'];//支付完成时间
						$rest = new Application_Model_Rest();
						
						/* $action = 'pay&transactionId='.$transaction_id.'&trade_state='.$trade_state.'&openid='.$openid.'&trade_type='.$trade_type.'&bank_type='.$bank_type.'&total_fee='.$total_fee.'&fee_type='.$fee_type.'&out_trade_no='.$out_trade_no.'&time_end='.$time_end; */
						$action = 'pay&transactionId='.$out_trade_no.'&platformId='.$transaction_id;
						$id = $oid;
						$res_pay = $rest->putUserOrder($action,$id);
						$has_paid = $res_pay->has_paid;
						if(!empty($res_pay)&&$has_paid==1){
							$this->_redirect('/order/success?oid='.$oid);
						}
					}	
				}
			}else{
				$this->_redirect('/error');
			}
	}	
    }

    public function statusAction()
    {
        $auth = new Application_Model_Auth();
		if(!$auth->isLoggedIn()){
			$this->_redirect('/login');
		}
		$session_uid = $auth->getUserId();
		$this->view->tel = $auth->getUserName();
		$req = $this->getRequest();
		$rest= new Application_Model_Rest();
		if($req->isGet()){
			$oid = $req->get('oid');
			$res = $rest->getUserOrderDetails($oid);
			if(empty($res)){
				$this->_redirect('/error');
			}
			$order_uid = $res->userid;
			if($session_uid != $order_uid){
				$rurl = '/order/list';
				$this->_redirect('/login?rurl='.$rurl);
			}
			$nameSpace = new Zend_Session_Namespace('siteid');
			$siteid = $nameSpace->siteid;
			if(!empty($siteid)){
				$this->view->siteid = $siteid;
			}
			if(!empty($res)){
//				foreach($res->statusList as $k=>$v){
//					if($res->sale_channel==1003){
//
//					}
//				}
					$this->view->res = $res;
			}

			if(!empty($oid))
				$this->view->oid = $oid;
	}	
    }

    public function zfbnotifydiffAction()
    {
        
    }

    public function notifyAction()
    {
        // action body
    }


}





























